import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

import java.io.*;

public class NetRequest extends AnAction {
    private Project project;
    //包名
    private String functionName  ;

    private String paramsName;//参数名字
    private String netAddressName;//网络地址
    private String dataTypeName;//数据类型
    private String interfaceFunctionName;//回调接口
    private String mModuleName;//回调接口
    private String packageName;//回调接口
    @Override
    public void actionPerformed(AnActionEvent e) {
        project = e.getData(PlatformDataKeys.PROJECT);
        init();
        refreshProject(e);
    }

    /**
     * 刷新项目
     *
     * @param e
     */
    private void refreshProject(AnActionEvent e) {
        e.getProject().getBaseDir().refresh(false, true);
    }


    /**
     * 初始化Dialog
     */
    private void init() {

        NetDialog netDialog = new NetDialog(new NetDialog.DialogCallBack() {
            @Override
            public void ok(String moduleName,String functionName, String paramsName, String netAddressName, String dataTypeName, String interfaceFunctionName) {
                packageName = "com." + moduleName.toLowerCase();
                mModuleName = moduleName;
               NetRequest .this. functionName  = functionName ;
               NetRequest .this. paramsName  = paramsName ;
               NetRequest .this. netAddressName  = netAddressName ;
               NetRequest .this. dataTypeName  = dataTypeName ;
               NetRequest .this. interfaceFunctionName  = interfaceFunctionName ;

                createKtFiles();
                Messages.showInfoMessage(project, "哈哈,create  code success", "title");

            }
        });


        netDialog.setVisible(true);

    }
    private String getAppPath() {

        String appPath = project.getBasePath() + "/" + mModuleName;
        return appPath;
    }

    private void createKtFiles() {
        String fileName = "";
        String content = "";
        String appPath = getAppPath();
        String packagePath = packageName.replace(".", "/");

        fileName = "Template.txt";
        content = ReadTemplateFile(fileName);
        content = dealTemplateContent(content);
        writeToFile(content, appPath + "/src/main/java/" + packagePath + "/" + "/template", functionName + ".kt");

    }
    /**
     * 读取模板文件中的字符内容
     *
     * @param fileName 模板文件名
     * @return
     */
    private String ReadTemplateFile(String fileName) {
        InputStream in = null;
        in = this.getClass().getResourceAsStream("/Template/" + fileName);
        String content = "";
        try {
            content = new String(readStream(in));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }


    private byte[] readStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
            inputStream.close();
        }

        return outputStream.toByteArray();
    }

    /**
     * 替换模板中字符
     *
     * @param content
     * @return
     */
    private String dealTemplateContent(String content) {
/**
 *
 * $functionParam  方法里面的参数
 *
 *
 *
 * $functionParamValue
 * $paramsMap
 *
 *
 */
        content = content.replace("$functionName", functionName);
        content = content.replace("$moduleName", mModuleName);
        content = content.replace("$interfaceFunctionName", interfaceFunctionName);
        content = content.replace("$dataTypeName", dataTypeName);
        content = content.replace("$netAddressName", netAddressName);


        if (paramsName.isEmpty()){
            content = content.replace("$functionParam", "");
            content = content.replace("$mfunctionParamValue", "");
            content = content.replace("$paramsMap", "");
        }else {

            String[] split = paramsName.split(",");
            StringBuilder s = new StringBuilder();
            StringBuilder s2 = new StringBuilder();
            StringBuilder s3 = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                s.append(split[i]).append(": String");
                s2.append(split[i]);
// params.put("cid",createCid)
                s3.append(" params.put(\""+split[i]+"\","+split[i]+")");
                s3.append("\n");

                if (i!=split.length-1){
                    s.append(",");
                    s2.append(",");
                }
            }
            content = content.replace("$functionParam", s.toString());
            content = content.replace("$mfunctionParamValue", s2.toString());

            content = content.replace("$paramsMap", s3.toString());


        }

        return content;
    }

    /**
     * 生成
     *
     * @param content   类中的内容
     * @param classPath 类文件路径
     * @param className 类文件名称
     */
    private void writeToFile(String content, String classPath, String className) {
        try {
            File floder = new File(classPath);
            if (!floder.exists()) {
                floder.mkdirs();
            }

            File file = new File(classPath + "/" + className);
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
